<?php

namespace app\service;

use app\model\ProjectMemberModel;
use app\tool\SingletonTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ProjectMemberService
{
    use SingletonTrait;

    /**
     * @param int $projectId
     * @param int $roleId
     * @return array
     */
    public function select(int $projectId, int $roleId)
    {
        $res = [];
        $serviceName = "teamones-saas";
        $endPoint = "project_member/select";
        $data = json_encode([
            "param" => [
                'filter' => [
                    'project_id' => $projectId,
                    'role_id' => $roleId,
                ],
                'page' => [1, 500],
            ]
        ]);
        $res = teamones_request($serviceName, $endPoint, $data);
        return array_column($res, null, 'id');
    }

    /**
     * 获取导演角色用户ids
     * @param $projectId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDirectorUserIds($projectId): array
    {
        // 查询所有用户是导演的角色
        $projectUserList = (new \app\model\ProjectMemberModel)->cache()->field('user_id')
            ->where('project_id', $projectId)
            ->whereRaw("role_id in (select id from role where code = 'director')")
            ->select();
        if (empty($projectUserList->toArray())) {
            return [];
        }
        return array_column($projectUserList->toArray(), 'user_id');
    }

    /**
     * 根据角色获取项目下用户ID列表
     * @param $projectId
     * @param $userRole
     * @return array
     */
    public function getProjectRoleUserIdList($projectId, $userRole): array
    {
        $userRoleList = split_array($userRole);
        if (empty($userRoleList)) {
            return [];
        }
        $projectUserList = ProjectMemberModel::where('project_id', $projectId)
            ->whereRaw("role_id in (" . RoleService::getInstance()->byCodeMap($userRoleList, false, 'id') . ")")
            ->column('user_id');
        return $projectUserList;
    }
}
